//
//  AppDelegate.m
//  dyseller
//
//  Created by 红喇叭 on 2017/6/1.
//  Copyright © 2017年 红喇叭. All rights reserved.
//

#import "AppDelegate.h"
#import "HLBTabBarVC.h"
#import "XGPush.h"
#import "XGSetting.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import "ConventionalLoginVC.h"
#import "BaseNavgationC.h"
#import "PayOrderViewController.h"
#import "CommentsNoticeVC.h"
#import "OrderNoticeVC.h"
#import "myWkWebViewController.h"
#import "NoticeListVCViewController.h"
#import <AudioToolbox/AudioToolbox.h>


#define XG_AppID 2200264480
#define XG_APPKEY @"IN538Q5WHF2T"

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0

#import <UserNotifications/UserNotifications.h>
@interface AppDelegate() <UNUserNotificationCenterDelegate>
@end
#endif
@interface AppDelegate (){
    BMKMapManager *_mapManager;
}

@end

@implementation AppDelegate
+ (AppDelegate *)delegate{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //启动BaiduMapManager 注册百度SDK
    _mapManager = [[BMKMapManager alloc]init];
    // 如果要关注网络及授权验证事件，请设定     generalDelegate参数
    BOOL ret = [_mapManager start:@"60INSbj57UG00KxhU1V7WplsioizK0U0"  generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    
    //打开信鸽的打印
    [[XGSetting getInstance] enableDebug:YES];
    
    [XGPush startApp:2200264480 appKey:@"IN538Q5WHF2T"];
    
    [XGPush isPushOn:^(BOOL isPushOn) {
        NSLog(@"[XGDemo] Push Is %@", isPushOn ? @"ON" : @"OFF");
    }];
    
    [self registerAPNS];
    
    [XGPush handleLaunching:launchOptions successCallback:^{
        NSLog(@"[XGDemo] Handle launching success");
    } errorCallback:^{
        NSLog(@"[XGDemo] Handle launching error");
    }];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor  whiteColor];
    
    NSDictionary *remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if(remoteNotification){
        isdelay = YES;
    }
    if([remoteNotification[@"pushType"] intValue] == 10000){
        [self LoginVC];
    }else{
        if([[NSUserDefaults standardUserDefaults] objectForKey:@"admin_id"]){
            
            [self showMainCtr];
            
        }else{
            [self LoginVC];
            
        }
    }

    [self.window makeKeyAndVisible];
    
    //注册
    [[UIApplication sharedApplication] registerForRemoteNotifications];

    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
//    [self PushViewController:launchOptions];
    
    //第一次安装时设置开启振动
    if(![userDefaults objectForKey:@"zhendongOn"]){
      [userDefaults setObject:@"1" forKey:@"zhendongOn"];
        
    }
    
    //解决IOS导航栏pop回去UIScrollView漂移问题
    if (@available(iOS 11, *)) {
        [UIScrollView appearance].contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    if([[UIApplication sharedApplication] isRegisteredForRemoteNotifications]){
        
    }else{
        
    }
    return YES;
}

/*- (void)PushViewController:(NSDictionary*)tfdic
{
    NSDictionary *remoteNotification = [tfdic objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
   
    int type =  [remoteNotification[@"pushType"] intValue];
    switch (type) {
        case 10001:
            case 10004:
            //新的订单点击
            [self jumpOrder:remoteNotification[@"orderSn"]];
            break;
        case 10002:
            //新的评论点击
            [self jumpComment];
            break;
        case 10003:
            //新的公告点击
            [self jumpAnnounCenment:remoteNotification[@"noticId"]];
            break;
        default:
            break;
    }

}*/


//点击订单·推送的处理
- (void)jumpOrder:(NSString *)orderID{
    HLBTabBarVC *tabVC;
    if ([[UIApplication sharedApplication].keyWindow.rootViewController isMemberOfClass:[HLBTabBarVC class]]){
        tabVC = (HLBTabBarVC*)[UIApplication sharedApplication].keyWindow.rootViewController;
    }
     BaseNavgationC *nav = (BaseNavgationC *)tabVC.viewControllers[1];
    if(!isdelay){
        tabVC.selectedIndex = 1;
    }else{
        nav = (BaseNavgationC *)tabVC.viewControllers[0];
    }
    isdelay = NO;
   
//    PayOrderViewController *vc = [[PayOrderViewController alloc] initWith:@[] style:1];
//    vc.orderStr = orderID;
//    vc.fromVC = 1;
    OrderNoticeVC *vc = [[OrderNoticeVC alloc] init];
    [nav pushViewController:vc animated:YES];

}

//点击评论推送的处理的
- (void)jumpComment{
    HLBTabBarVC *tabVC;
    if ([[UIApplication sharedApplication].keyWindow.rootViewController isMemberOfClass:[HLBTabBarVC class]]){
        tabVC = (HLBTabBarVC*)[UIApplication sharedApplication].keyWindow.rootViewController;
    }
    BaseNavgationC *nav = (BaseNavgationC *)tabVC.viewControllers[1];
    if(!isdelay){
        tabVC.selectedIndex = 1;
    }else{
        nav = (BaseNavgationC *)tabVC.viewControllers[0];
    }
    isdelay = NO;
    CommentsNoticeVC *vc = [[CommentsNoticeVC alloc] init];
    [nav pushViewController:vc animated:YES];
}


//点击系统公告的通知
- (void)jumpAnnounCenment:(NSString *)noticID{
    HLBTabBarVC *tabVC;
    if ([[UIApplication sharedApplication].keyWindow.rootViewController isMemberOfClass:[HLBTabBarVC class]]){
        tabVC = (HLBTabBarVC*)[UIApplication sharedApplication].keyWindow.rootViewController;
    }
    
        
    BaseNavgationC *nav = (BaseNavgationC *)tabVC.viewControllers[1];
    if(!isdelay){
        tabVC.selectedIndex = 1;
    }else{
        nav = (BaseNavgationC *)tabVC.viewControllers[0];
    }
    isdelay = NO;
    myWkWebViewController *vc = [[myWkWebViewController alloc] init];
    NSString *url = [NSString stringWithFormat:@"%@/ShopApi/Html/itemDetail?noticeId=%@&flag=1",APP_HOST_ADDRESS,noticID];
    vc.myurl = url;
    vc.toTitle = @"公告详情";
   
    [nav pushViewController:vc animated:YES];
    
}

//登录
- (void)LoginVC{
    
    ConventionalLoginVC *login = [[ConventionalLoginVC alloc] init];
    BaseNavgationC *nav = [[BaseNavgationC alloc] initWithRootViewController:login];
    login.title = @"登录";
    self.window.rootViewController = nav;
    
}

- (void)showMainCtr{
    HLBTabBarVC *mainVC = [[HLBTabBarVC alloc] init];
   // UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:mainVC];
    
    self.window.rootViewController = mainVC;
    
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    if(deviceToken==nil){
        alert(@"设备存在问题，无法支持推送功能");
      //  return ;
    }
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
    [dateFormatter setDateFormat:@"YYYY/MM/dd/hh/mm/ss/SS"];//设定时间格式,这里可以设置成自己需要的格式
    NSString *dateString = [dateFormatter stringFromDate:currentDate];//将时间转化成字符串
    NSString *accout = [NSString stringWithFormat:@"honglabaTestsss_%@",dateString];
    
    
    NSString *deviceTokenStr = [XGPush registerDevice:deviceToken account:accout successCallback:^{
        NSLog(@"[XGDemo] register push success");
    } errorCallback:^{
        NSLog(@"[XGDemo] register push error");
        
        [userDefaults setObject:deviceToken forKey:@"deviceToken"];
    }];
    NSLog(@"[XGDemo] device token is %@", deviceTokenStr);
    [userDefaults setObject:deviceTokenStr forKey:@"HLBdeviceToken"];
    [userDefaults synchronize];
    
    
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"[XGDemo] register APNS fail.\n[XGDemo] reason : %@", error);
}


/**
 收到通知的回调
 
 @param application  UIApplication 实例
 @param userInfo 推送时指定的参数
 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    NSLog(@"[XGDemo] receive Notification");
    [XGPush handleReceiveNotification:userInfo
                      successCallback:^{
                          NSLog(@"[XGDemo] Handle receive success");
                      } errorCallback:^{
                          NSLog(@"[XGDemo] Handle receive error");
                      }];
    
}


/**
 收到静默推送的回调
 
 @param application  UIApplication 实例
 @param userInfo 推送时指定的参数
 @param completionHandler 完成回调
 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@"[XGDemo] receive slient Notification");
    NSLog(@"[XGDemo] userinfo %@", userInfo);
    [XGPush handleReceiveNotification:userInfo
                      successCallback:^{
                          NSLog(@"[XGDemo] Handle receive success");
                      } errorCallback:^{
                          NSLog(@"[XGDemo] Handle receive error");
                      }];
    
    [self notice_Transfer:userInfo];
    //APP处于前台运行
    if(application.applicationState == UIApplicationStateActive){
        int type =  [userInfo[@"pushType"] intValue];
        if([[userDefaults objectForKey:@"zhendongOn"] isEqualToString:@"1"]){
            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        }
        switch (type) {
            case 10000:
                //异常登录的通知处理
                [self abnormalLogin];
                break;
            case 10001:
            case 10004:
            {
                NSString *path = [[NSBundle mainBundle] pathForResource:@"order" ofType:@"wav"];
                //组装并播放音效
                SystemSoundID soundID;
                
                NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
                
                AudioServicesCreateSystemSoundID((__bridge CFURLRef)filePath, &soundID);
                
                AudioServicesPlaySystemSound(soundID);

            }
                break;
            case 10002:
            {
                NSString *path = [[NSBundle mainBundle] pathForResource:@"comment" ofType:@"wav"];
                //组装并播放音效
                SystemSoundID soundID;
                
                NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
                
                AudioServicesCreateSystemSoundID((__bridge CFURLRef)filePath, &soundID);
                
                AudioServicesPlaySystemSound(soundID);

            }
                break;
            case 10003:
            {
                NSString *path = [[NSBundle mainBundle] pathForResource:@"notice" ofType:@"wav"];
                //组装并播放音效
                SystemSoundID soundID;
                
                NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
                
                AudioServicesCreateSystemSoundID((__bridge CFURLRef)filePath, &soundID);
                
                AudioServicesPlaySystemSound(soundID);

            }
                
                break;
            default:
                break;
        }

        NSLog(@"活跃");
    }else if(application.applicationState == UIApplicationStateInactive){
      //点击通知进来
        NSLog(@"活跃");
        [self NotifiCation:userInfo];
        
    }else if(application.applicationState == UIApplicationStateBackground){
        //APP处于后台挂起状态
        NSLog(@"=======");
       
    }
    

    //completionHandler(UIBackgroundFetchResultNewData);
     completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}

// iOS 10 新增 API
// iOS 10 会走新 API, iOS 10 以前会走到老 API
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// App 用户点击通知的回调
// 无论本地推送还是远程推送都会走这个回调
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler {
    NSLog(@"[XGDemo] click notification");
    [XGPush handleReceiveNotification:response.notification.request.content.userInfo
                      successCallback:^{
                          NSLog(@"[XGDemo] Handle receive success");
                      } errorCallback:^{
                          NSLog(@"[XGDemo] Handle receive error");
                      }];
    //APP在前台运行或者后台运行
//    if( [UIApplication sharedApplication].applicationState == UIApplicationStateActive || [UIApplication sharedApplication].applicationState == UIApplicationStateInactive)
//    {

    //}
    [self NotifiCation:response.notification.request.content.userInfo];
    
    completionHandler();
}



// App 在前台弹通知需要调用这个接口
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
    NSLog(@"收到推送");
    /*推送参数中：pushType
    10000:登录标识
    10001:订单标识
    10002:评论标识
    10003:公告标识*/
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"honglaba" ofType:@"wav"];
//    
//    NSLog(@"path---%@",path);
//    
//    //组装并播放音效
//    
//    SystemSoundID soundID;
//    
//    NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
//    
//    AudioServicesCreateSystemSoundID((__bridge CFURLRef)filePath, &soundID);
//    
//    AudioServicesPlaySystemSound(soundID);
    

    [self notice_Transfer:notification.request.content.userInfo];
    
    completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}
#endif



- (void)applicationWillResignActive:(UIApplication *)application {

}


- (void)NotifiCation:(NSDictionary *)userInfo{
    HLBTabBarVC *tabVC;
    if ([[UIApplication sharedApplication].keyWindow.rootViewController isMemberOfClass:[HLBTabBarVC class]]){
        tabVC = (HLBTabBarVC*)[UIApplication sharedApplication].keyWindow.rootViewController;
    }
    int type =  [userInfo[@"pushType"] intValue];
    NSDictionary *remoteNotification = userInfo;
    switch (type) {
        case 10000:
            //异地登录点击
            [userDefaults removeObjectForKey:@"admin_id"];
            [self LoginVC];
            break;
        case 10001:
            case 10004:
            //新的订单点击
            if([[self topViewController] isMemberOfClass:[OrderNoticeVC class]]){
                
                [[NSNotificationCenter defaultCenter]postNotificationName:@"news_OrderList" object:nil userInfo:nil];
            }else{
                //新的评论点击
                 [self jumpOrder:remoteNotification[@"orderSn"]];
            }
            break;
        case 10002:
            //如果停留的页面是评论列表页面
            if([[self topViewController] isMemberOfClass:[CommentsNoticeVC class]]){
                
                [[NSNotificationCenter defaultCenter]postNotificationName:@"news_CommentList" object:nil userInfo:nil];
            }else{
                //新的评论点击
                [self jumpComment];
            }
            break;
        case 10003:
            //新的公告点击
            [self jumpAnnounCenment:remoteNotification[@"noticId"]];
            
            break;
        default:
            break;
    }
    
}

//收到通知发送消息的处理
- (void)notice_Transfer:(NSDictionary *)userInfo{
    int type =  [userInfo[@"pushType"] intValue];
    if([[userDefaults objectForKey:@"zhendongOn"] isEqualToString:@"1"]){
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }
    switch (type) {
        case 10000:
            //异地登录通知
            [self abnormalLogin];
            break;
        case 10001:
            case 10004:
            //新的订单通知
            if([[self topViewController] isMemberOfClass:[OrderNoticeVC class]]){
                
                [[NSNotificationCenter defaultCenter]postNotificationName:@"news_OrderList" object:nil userInfo:nil];
            }else{
                [[NSNotificationCenter defaultCenter]postNotificationName:@"news_order" object:nil userInfo:nil];
            }

            break;
        case 10002:
            //新的评论通知
            if([[self topViewController] isMemberOfClass:[CommentsNoticeVC class]]){
                
                [[NSNotificationCenter defaultCenter]postNotificationName:@"news_CommentList" object:nil userInfo:nil];
            }else{
               [[NSNotificationCenter defaultCenter]postNotificationName:@"news_Comment" object:nil userInfo:nil];
            }
            break;
        case 10003:
            //新的公告通知
            [[NSNotificationCenter defaultCenter]postNotificationName:@"news_Admins" object:nil userInfo:nil];
            break;
        default:
            break;
    }
    
    
    
}
//IOS10以下系统在前台时出现异地登录时的处理
- (void)abnormalLogin{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"账号异常" message:@"您的账号已在其他终端登录!!" preferredStyle:UIAlertControllerStyleAlert];
    //添加取消到UIAlertController中
    [alertController addAction:[UIAlertAction actionWithTitle:@"去登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [userDefaults removeObjectForKey:@"admin_id"];
        [self LoginVC];
        
    }]];
   
    [[self topViewController] presentViewController:alertController animated:YES completion:nil];
}
//获取主屏幕当前的UIViewController
- (UIViewController *)topViewController {
    UIViewController *resultVC;
    resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}

- (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)registerAPNS {
    float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
    if (sysVer >= 10) {
        // iOS 10
        [self registerPush10];
    } else if (sysVer >= 8) {
        // iOS 8-9
        [self registerPush8to9];
    } else {
        // before iOS 8
        [self registerPushBefore8];
    }
#else
    if (sysVer < 8) {
        // before iOS 8
        [self registerPushBefore8];
    } else {
        // iOS 8-9
        [self registerPush8to9];
    }
#endif
}

- (void)registerPush10{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    
    
    [center requestAuthorizationWithOptions:UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
        }
    }];
    
    [[UIApplication sharedApplication] registerForRemoteNotifications];
#endif
}

- (void)registerPush8to9{
    UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
    UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
}

- (void)registerPushBefore8{
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}


- (void)loadNetwork{
    
    

}

@end
